import React, { useEffect, useState } from "react";
import Taro, { useRouter } from "@tarojs/taro";
import { View, Text, Input, Form, Button, Image } from "@tarojs/components";
import logo from "@/images/logo.jpg";
import rightIcon from "@/images/icon_line_arrow.png";
import { setToken } from "@/src/service";
import * as api from "./api";
import * as collectApi from "../collectList/api";
import "./index.scss";

const Index: React.FC<{}> = () => {
  const router = useRouter();
  const [code, setCode] = useState("");
  console.log("router---->>", router);

  useEffect(() => {
    Taro.login({
      success: async (res) => {
        if (res.code) {
          setCode(res.code);
        } else {
          console.log("登录失败！" + res.errMsg);
        }
      },
    });
  }, []);

  // 手机号登陆
  const onGetPhoneNumber = async (e) => {
    const detail = e.detail;
    console.log("e.detail--->>", e);
    if (detail.errMsg !== "getPhoneNumber:ok") {
      return;
    }

    try {
      // const sessionData = await Taro.checkSession();
      // console.log("Taro.checkSession()------>>>", sessionData);
      const { result, status } = await api.customer_account_wechatregister({
        data_info: JSON.stringify({
          code: code,
          encrypted_data: detail.encryptedData,
          iv: detail.iv,
        }),
      });
      if (status === "ok") {
        console.log("result------->>>", result);
        if (result.access_token) {
          setToken({
            ...result,
          });
          console.log("2222--->>");
          getCollectList();
          if (router.params.params) {
            const params = JSON.parse(router.params.params);
            Taro.redirectTo({
              url: `/pages/${params.redirectUrl}/index?${params.params.key}=${params.params.value}`,
            });
          } else {
            Taro.navigateBack();
          }
        }
      } else {
        console.log("新用户暂无token");
      }
    } catch (err) {
      console.log("err--------->>>", err);
    } finally {
      Taro.hideLoading();
    }
  };

  const getCollectList = async () => {
    const { result, status } = await collectApi.customer_collection_getallcollectionsids({});
    if (status === "ok") {
      console.log("result---->>", result);
      Taro.setStorageSync('collectIds',result.goods_ids)
    }
  };

  return (
    <View className="login-guide-page">
      <Image className="logo" src={logo} mode="widthFix" />
      <Button
        className="phone-login-btn"
        openType="getPhoneNumber"
        onGetPhoneNumber={onGetPhoneNumber}
      >
        授权手机号一键登陆
      </Button>

      <View
        className="switch"
        onClick={() => {
          if (router.params.params) {
            Taro.navigateTo({
              url: `/pages/login/index?params=${router.params.params}`,
            });
          } else {
            Taro.navigateTo({
              url: "/pages/login/index",
            });
          }
        }}
      >
        <Text>验证码登陆</Text>
        <Image src={rightIcon} />
      </View>
    </View>
  );
};

export default Index;
